<template>
  <div>
    <el-row>
      <div class="slideshow-container" @mouseenter="pauseAutoplay" @mouseleave="resumeAutoplay"
        :style="{backgroundImage: 'url(' + slides[currentSlideBg].src + ')'}">
        <transition name="slide-fade" mode="out-in">
          <div class="slide" :key="currentSlideIndex"
            :style="{ height: (windowStore.winHeight - 16 - 32) / 2 + 'px', backgroundImage: 'url(' + slides[currentSlideIndex].src + ')' }">
            <img :src="slides[currentSlideIndex].src" />
            <div class="overlay"></div>
          </div>
        </transition>
        <!-- 导航点 -->
        <div class="indicator">
          <span v-for="(slide, index) in slides" :key="index" class="dot"
            :class="{ active: index === currentSlideIndex }" @click="goToSlide(index)"></span>
        </div>
        <!-- 标题 -->
        <div class="caption" v-if="slides[currentSlideIndex].caption">
          {{ slides[currentSlideIndex].caption }}
        </div>
      </div>
    </el-row>
    <el-collapse v-model="activeNames">
      <el-collapse-item title="&nbsp;&nbsp;快捷方式" name="shortcut">
        <div class="flex-container">
          <div class="scroll-container"
            :style="{height: (windowStore.winHeight - 16 - 32) / 2 - 95 - 12 - (windowStore.isMaximized ? 18 : 0) + 'px'}">
            <div id="drop-area" class="avatar-uploader">
              <el-icon class="avatar-uploader-icon">
                <Plus />
              </el-icon>
            </div>
            <!-- 左侧可拖拽链接列表 -->
            <el-tag v-for="(link, index) in links" :key="link.name" type="info" effect="plain" class="link-item"
              closable @click="handleLinkClick(link)" @close="handleClose(link.fileName)">
              <span class="link-item-icon"><img :src="link.icon"></span>
              <span class="link-item-title">{{ link.name }}</span>
            </el-tag>
          </div>
        </div>
      </el-collapse-item>
    </el-collapse>
  </div>
</template>
<script>
  import { Plus } from '@element-plus/icons-vue'
  import { useWindowStore } from '/src/stores/windowStore';
  import { ipcRenderer } from 'electron';

  export default {
    name: 'Home',
    components: { Plus },
    data() {
      return {
        links: [],
        isMaximized: false,
        activeNames: ['shortcut'],
        slides: [{ src: 'favicon.ico', caption: '暂无图片' }],
        currentSlideIndex: 0,
        currentSlideBg: 0,
        autoplayInterval: null,
        autoplayDelay: 5000,
        isPaused: false
      };
    },
    setup() {
      const windowStore = useWindowStore();
      return { windowStore };
    },
    mounted() {
      const dropArea = document.getElementById('drop-area');
      dropArea.addEventListener('dragover', (event) => {
        event.preventDefault();
        dropArea.style.backgroundColor = "lightblue";
      }, false);
      dropArea.addEventListener('dragleave', () => {
        dropArea.style.backgroundColor = "";
      }, false);
      dropArea.addEventListener('drop', async (event) => {
        event.preventDefault();
        dropArea.style.backgroundColor = "";
        const files = event.dataTransfer.files;
        if (files.length > 0) {
          // 假设我们只处理第一个文件
          const file = files[0];
          console.log(`Dropped file name: ${file.name}`);
          if (file.name.toLowerCase().endsWith('.lnk') || file.name.toLowerCase().endsWith('.exe')) {
            let fileName = file.name.split('.').slice(0, -1).join('.');
            let rows = this.links.filter(link => link.name === fileName);
            if (rows.length === 0) {
              console.log(`Dropped file path: ${file.path}`);
              try {
                const result = await ipcRenderer.invoke('get-icon', file.name, file.path);
                if (result.code == 200) {
                  let data = {
                    name: fileName,
                    fileName: file.name,
                    lnk: file.path,
                    url: result.data.exePath.toLowerCase().endsWith('.exe') ? result.data.exePath : file.path,
                    icon: `data:image/png;base64,${result.data.iconBase64}`
                  };
                  await ipcRenderer.invoke('save-link', file.name, file.path);
                  this.links.push(data);
                } else {
                  console.log(result);
                }
              } catch (error) {
                console.error('获取图标失败:', error);
              }
            }
          }
        }
      }, false);

      this.getSlides();
      this.startAutoplay();
      this.loadLinks();
    },
    methods: {
      async getSlides() {
        this.slides = [
          { src: await ipcRenderer.invoke('read-image-file', '../slide/1.jpg'), caption: '这是第一张幻灯片' },
          { src: await ipcRenderer.invoke('read-image-file', '../slide/2.jpg'), caption: '这是第二张幻灯片' },
          { src: await ipcRenderer.invoke('read-image-file', '../slide/3.jpg'), caption: '这是第三张幻灯片' }
        ];
      },
      async handleLinkClick(link) {
        try {
          const result = await ipcRenderer.invoke('onclick-exe', link.lnk);
          console.log('执行结果:', result);
        } catch (error) {
          console.error('执行失败:', error);
        }
      },
      async handleClose(fileName) {
        await ipcRenderer.invoke('del-link', fileName);
        this.links = this.links.filter(link => link.fileName !== fileName);
      },
      nextSlide() {
        this.currentSlideBg = this.currentSlideIndex;
        this.currentSlideIndex = (this.currentSlideIndex + 1) % this.slides.length;
      },
      stopAutoplay() {
        clearInterval(this.autoplayInterval);
        this.autoplayInterval = null;
      },
      pauseAutoplay() {
        this.isPaused = true;
      },
      resumeAutoplay() {
        this.isPaused = false;
      },
      startAutoplay() {
        if (this.autoplayInterval) return;
        this.autoplayInterval = setInterval(() => {
          if (!this.isPaused) {
            this.nextSlide();
          }
        }, this.autoplayDelay);
      },
      async loadLinks() {
        let _data = await ipcRenderer.invoke('get-links');
        _data.data.forEach(async (item) => {
          if (item.fileName.toLowerCase().endsWith('.lnk') || item.fileName.toLowerCase().endsWith('.exe')) {
            let fileName = item.fileName.split('.').slice(0, -1).join('.');
            try {
              const result = await ipcRenderer.invoke('get-icon', item.fileName, item.filePath);
              if (result.code == 200) {
                this.links.push({
                  name: fileName,
                  fileName: item.fileName,
                  lnk: item.filePath,
                  url: result.data.exePath.toLowerCase().endsWith('.exe') ? result.data.exePath : item.filePath,
                  icon: `data:image/png;base64,${result.data.iconBase64}`
                });
              } else {
                console.log(result);
              }
            } catch (error) {
              console.error('获取图标失败:', error);
            }
          }
        });
      },
      goToSlide(index) {
        this.currentSlideBg = this.currentSlideIndex;
        this.currentSlideIndex = index;
      }
    },
    beforeUnmount() {
      clearInterval(this.autoplayInterval);
      this.autoplayInterval = null;
    }
  };
</script>
<style>
  /* 修改 el-collapse-item 的外层容器圆角 */
  .el-collapse {
    margin-top: 10px;
    /* 设置你需要的圆角大小 */
    border: 1px solid var(--el-border-color-light);
    border-top: 1px solid var(--el-border-color-light);
  }

  .el-collapse-item__wrap {
    border-top: 1px solid var(--el-border-color-light);
    border-bottom: 1px solid var(--el-border-color-light);
  }

  :deep(.el-collapse-item__header) {
    border-top-left-radius: 4px;
    border-top-right-radius: 4px;
    padding-left: 5px;
    border-bottom: 1px solid var(--el-border-color-light);
  }

  .el-collapse-item__content {
    border-bottom-color: #00000012;
    padding-bottom: 0 !important;
    padding-top: 0;
  }

  .el-tag {
    border-color: var(--el-border-color-lighter);
  }

  .flex-container {
    background-color: var(--el-bg-color);
  }

  .scroll-container {
    overflow-y: auto;
    padding: 2px 10px 0 0;
    padding-right: 4px;
  }

  /* 滚动条样式 */
  .scroll-container::-webkit-scrollbar {
    width: 8px;
  }

  /* 滚动条轨道 */
  .scroll-container::-webkit-scrollbar-track {
    background-color: transparent;
  }

  /* 滚动条滑块 */
  .scroll-container::-webkit-scrollbar-thumb {
    border-radius: 8px;
    background-color: var(--el-color-primary);
    /* 可以换成你喜欢的颜色，例如 element-ui 的灰色 */
  }

  /* 悬停时的滑块颜色 */
  .scroll-container::-webkit-scrollbar-thumb:hover {
    background-color: var(--el-color-primary-light-3);
  }

  .link-item {
    height: 42px;
    cursor: pointer;
    margin: 5px;
  }

  .link-item .link-item-icon img {
    width: 32px;
    height: 32px;
  }

  .link-item .link-item-title {
    height: 32px;
    line-height: 32px;
    float: right;
    margin-left: 5px;
    user-select: none;
    /* 禁止选中文本 */
    -webkit-user-select: none;
    /* 兼容 Safari */
    -moz-user-select: none;
    /* 兼容 Firefox */
    -ms-user-select: none;
    /* 兼容 IE/Edge */
  }

  .avatar-uploader {
    width: 92px;
    height: 92px;
    border: 1px dashed var(--el-border-color);
    float: left;
    border-radius: 5px;
    margin: 5px;
  }

  .avatar-uploader .el-upload {
    border: 1px dashed var(--el-border-color);
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
    transition: var(--el-transition-duration-fast);
  }

  .avatar-uploader .el-upload:hover {
    border-color: var(--el-color-primary);
  }

  .el-icon.avatar-uploader-icon {
    font-size: 28px;
    color: var(--el-color);
    width: 92px;
    height: 92px;
    text-align: center;
  }

  .no-gutter {
    margin-left: 0 !important;
    margin-right: 0 !important;
  }
</style>
<style>
  .slideshow-container {
    position: relative;
    margin: auto;
    text-align: center;
    overflow: hidden;
    width: 100%;
    background-size: cover;
    background-repeat: no-repeat;
    /* background: radial-gradient(ellipse at center, rgba(131, 131, 131, 0.8) 0%, rgba(100, 100, 100, 0.95) 100%) */
  }

  .slide-fade-enter-active {
    transition: all 0.8s ease;
    transform-origin: center center;
  }

  .slide-fade-leave-active {
    transition: all 0.6s ease;
    opacity: 0;
    transform: scale(1.2) rotate(-2deg);
  }

  .slide-fade-enter-from {
    opacity: 0;
    transform: scale(0.8) rotate(2deg);
  }

  .nav-button {
    font-size: 32px;
    background-color: rgba(0, 0, 0, 0.4);
    border-radius: 50%;
    padding: 12px;
    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.4);
    transition: all 0.3s ease;
  }

  .nav-button:hover {
    background-color: rgba(0, 0, 0, 0.7);
    transform: scale(1.2);
    box-shadow: 0 6px 16px rgba(0, 0, 0, 0.6);
  }

  .indicator {
    position: absolute;
    bottom: 10px;
    left: 50%;
    transform: translateX(-50%);
    display: flex;
    gap: 8px;
    z-index: 9;
  }

  .dot {
    width: 10px;
    height: 10px;
    border-radius: 50%;
    background-color: rgba(255, 255, 255, 0.6);
    cursor: pointer;
    transition: all 0.3s ease;
  }

  .dot.active {
    background-color: #fff;
    transform: scale(1.4);
    box-shadow: 0 0 8px rgba(255, 255, 255, 0.8);
  }

  .slide {
    position: relative;
    overflow: hidden;
    background-size: cover;
    background-repeat: no-repeat;
  }

  .slide img {
    opacity: 0;
    transition: opacity 0.3s ease;
  }

  .slide img.loaded {
    opacity: 1;
  }

  .overlay {
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    z-index: 2;
    background: linear-gradient(to bottom,
        rgba(235, 235, 235, 0.5) 0%,
        rgba(114, 113, 113, 0) 10%,
        rgba(158, 158, 158, 0) 90%,
        rgba(61, 61, 61, 0.5) 100%);
  }

  .caption {
    position: absolute;
    bottom: 40px;
    left: 50%;
    transform: translateX(-50%);
    font-size: 20px;
    text-shadow: 0 2px 6px rgba(0, 0, 0, 0.6);
    z-index: 3;
    animation: fadeIn 0.5s ease-in-out;
  }

  @keyframes fadeIn {
    from {
      opacity: 0;
      transform: translateX(-50%) translateY(10px);
    }

    to {
      opacity: 1;
      transform: translateX(-50%) translateY(0);
    }
  }
</style>